package com.asking.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;

import java.io.File;

public class FileSaveUtils {

    /**
     * 上传文件
     * @param key   文件名
     * @param localFile     文件
     * @return
     */
    public static String putFile(String key,File localFile) {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials("AKIDNYT9Z8CbT6VfbIAxvfAQSFo8D3e0kzd2", "IMBm7E5g15tQhhRvDF0VkiQu99uRjma9");
// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
// 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
// bucket名需包含appid
        String bucketName = "videoplatform-1256679754";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
// 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard_IA);
        try {
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            String etag = putObjectResult.getETag();
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }

// 关闭客户端
        cosclient.shutdown();
        System.out.println("videoplatform-1256679754.cos.ap-guangzhou.myqcloud.com/"+key);
        return "videoplatform-1256679754.cos.ap-guangzhou.myqcloud.com/"+key;
    }


}
